﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using HtmlParser.Html;
using HtmlParser.Dom;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace RoughBrowser
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private CookieContainer container = new CookieContainer();
        private ObservableCollection<Node> nodesList = new ObservableCollection<Node>();
        public MainWindow()
        {
            InitializeComponent();

        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {

            string baseUri = this.txtUrl.Text.Trim();
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUri);
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
                request.Method = "GET";
                request.CookieContainer = container;
                request.BeginGetResponse(e1 =>
                {

                    HttpWebRequest request1 = (HttpWebRequest)e1.AsyncState;
                    HttpWebResponse response = (HttpWebResponse)request1.EndGetResponse(e1);
                    var encoding = response.CharacterSet;
                    StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(encoding));
                    string html = reader.ReadToEnd();
                    var hDoc = new HtmlDocumentEx();
                    HtmlElement[] doc = hDoc.Parse(html);

                    Print(doc);
                    this.Dispatcher.BeginInvoke((Action)delegate()
                    {
                        treeStruct.ItemsSource = nodesList;
                    });

                }, request);
            }
            catch (Exception ex)
            {
                ShowError(ex.ToString());
            }
        }

        // private void 
        private void Print(HtmlElement[] nodes)
        {

            for (int i = nodes.Length - 1; i >= 0; i--)
            {
                var item = nodes[i];
                var newNode = new Node() { Name = item.Name, NodeTitle = item.Value };
                nodesList.Add(newNode);
                if (item.ChildNodes != null && item.ChildNodes.Count > 0)
                {
                    PrintChild(item, newNode, 0);
                }
            }

        }// end for method

        private void PrintChild(HtmlElement parent, Node newNode, int index)
        {
            for (int i = parent.ChildNodes.Count - 1; i >= 0; i--)
            {
                var item = parent.ChildNodes[i];
                var newNode1 = new Node() { Name = item.Name, NodeTitle = item.Value };
                newNode.Children.Add(newNode1);
                if (item.ChildNodes != null && item.ChildNodes.Count > 0)
                {
                    PrintChild(item as HtmlElement, newNode1, index + 1);
                }
            }
        }

        private void ShowError(string msg)
        {
            MessageBox.Show(msg);
        }
    }// end for method

    public class Node : INotifyPropertyChanged
    {
        private string _Name;
        private string _NodeValue;
        private string _title;
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
                NotifyPropertyChanged("Name");
            }
        }
        public string NodeValue
        {
            get
            {
                return _NodeValue;
            }
            set
            {
                _NodeValue = value;
                NotifyPropertyChanged("NodeValue");
            }
        }
        public string NodeTitle
        {
            get
            {
                if (Name == "#text")
                {
                    return NodeValue;
                }
                return Name;
            }
            set
            {
                _title = value;
                NotifyPropertyChanged("NodeTitle");
            }
        }

        private ObservableCollection<Node> _Children;
        public ObservableCollection<Node> Children
        {
            get
            {
                if (_Children == null)
                {
                    _Children = new ObservableCollection<Node>();
                }
                return _Children;
            }
            set
            {
                if (_Children == null)
                {
                    _Children = new ObservableCollection<Node>();
                }
                NotifyPropertyChanged("Children");
                _Children = value;
            }
        }



        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
